//============================================================================
// Name        : file_recv.cpp
// Author      : Jonathan Ellithorpe and Allen Lee
// Version     :
// Copyright   : UC Berkeley
// Description : Program that receives a file using the GNUT protocol
//============================================================================

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include "ServerConnection.h"

using namespace std;

int main(int argc, char* argv[]) {

	// some variables 
	char* port;
	char* filename;
	int fd;

	// parse the arguments
	if( argc != 3 ){
		// panic! at the disco
		printf("Usage: port filename\n");
		exit(1);
	} else
	{
		port = argv[1];
		filename = argv[2];

	}

	// open the file for writing
	string path("./");
	path.append(filename);

	verbose ? printf("opening file: %s\n", path.c_str()):1;
	if( (fd = creat(path.c_str(), S_IRWXU)) == -1 )
		printf("failed to open file\n");

	ServerConnection SConn = ServerConnection( atoi(port), AdvertisedWindow);

	if( SConn.accept() == -1 )
		printf("ERROR -- could not accept connection\n");
	else if( SConn.recv(fd) == -1 )	
		printf("ERROR -- didn't receive file correctly\n");

	SConn.closeConnection();
	
	close(fd);

	return EXIT_SUCCESS;
}
